// +---------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +---------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +---------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +---------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +---------------------------------------------------------------------

import { HTTP_REQUEST_URL, HEADER, TOKENNAME} from '@/config/app';
import { toLogin, checkLogin,loginUserinfo } from '../libs/login';
import store from 'store';

/**
 * 发送请求
 */
function baseRequest(url, method, data, {noAuth = false, noVerify = false})
{
  let Url = HTTP_REQUEST_URL, header = HEADER;
  if (!noAuth) {
    //登录过期自动登录
	if(!store.state.app.token){
		uni.switchTab({
		    url: '/pages/user/user.vue'
		});
		// toLogin();
		// return Promise.reject({msg:'未登陆'});
	}
  }
 if (store.state.app.token) header[TOKENNAME] = 'Bearer ' + store.state.app.token;
  return new Promise((reslove, reject) => {
    uni.request({
      url: Url + '/api/' + url,
      method: method || 'GET',
      header: header,
      data: data || {},
      success: (res) => {
		  let flaglogin = false;
        if (noVerify)
          reslove(res.data, res);
        else if (res.data.code == 200)
          reslove(res.data, res);
		else if (res.data.code == -5)
		  reject(res.data, res);
        else if (res.data.code == -2) {		
			if(flaglogin == false){
				flaglogin = true;
				// uni.clearStorage()
					try {
					// uni.clearStorageSync()
					 uni.removeStorageSync('USER_INFO');
					  uni.removeStorageSync('isLogin');
					  uni.removeStorageSync("UNI-APP-CRMEB:TAG");
					  uni.removeStorageSync("__DC_STAT_UUID");
					setTimeout(() =>{
							let page = getCurrentPages().pop();  //跳转页面成功之后
							if (!page) return;  
							page.onLoad(); //如果页面存在，则重新刷新页面
							// page.onShow();
							let pages = getCurrentPages(); //获取所有页面栈实例列表
							let nowPage = pages[pages.length - 2]; //当前页页面实例
							// let nowPager = pages[pages.length - 2];
							nowPage.$vm.userInfo = {};
							nowPage.$vm.svipScore = 0;
							nowPage.$vm.state = 2;
							store.commit('SETISLOGIN',false);
					},500)
				} catch(e) {
					// Do something when catch error
				}
			}
			uni.showModal({
			    title: '提示',
			    content: '请登录',
			    success: function (res) {
			        if (res.confirm) {
			            console.log('用户点击确定');
						 // uni.removeStorageSync('code','UNI-APP-CRMEB:TAG','LOGIN_STATUS_TOKEN','USER_INFO','isLogin');
									// loginUserinfo();
						uni.switchTab({
						    url: '/pages/user/user'
						});
			        } else if (res.cancel) {
			            console.log('用户点击取消');
						uni.navigateBack({
							delta:1
						})
			        }
			    }
			});
		}
		else if(res.data.code == 400){
			reject(res.data.msg);
			uni.showToast({
			    title: res.data.msg,
				icon:"none",
			    duration: 1000
			});
		}
		else if(res.data.code == 410010){
			uni.showModal({
			    title: '提示',
			    content: res.msg,
				showCancel: false,
				confirmText:'我知道了'
			}); 
        } else
		  // reject(res.data, res);
          reject(res.data.msg || '系统错误');
      },
      fail: (msg) => {
        reject('请求失败');
      }
    })
  });
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;